import { v4 as uuidv4 } from 'uuid';
import formidable from 'formidable';
import xlsx from 'xlsx';


export default {
  use(app, knex) {

    //新增tag
    app.post('/tag/add', async function (req, res) {
      //同一设备下节点不得超过512个
      const counts = await knex('tag')
        .where('parent_id', '=', req.body.parent_id)
        .count('parent_id as total')
      if (counts[0].total >= 512) {
        res.send({
          code: 1,
          message: '同一设备下节点不得超过512个'
        })
        return;
      }
      //是否命名重复
      const sameNames = await knex('tag')
        .where('parent_id', '=', req.body.parent_id)
        .andWhere('name', '=', req.body.name)
      if (sameNames.length > 0) {
        res.send({
          code: 1,
          message: `节点名称重复请修改后重新提交`,
        })
        return;
      }

      knex('tag')
        .insert({ id: uuidv4(), ...req.body })
        .then(row => {
          res.send({
            code: 0,
            message: '新增tag成功'
          })
        })
        .catch(err => {
          res.send({
            code: 1,
            message: err
          })
        })

    })


    //从文件导入tag
    app.post('/tag/addByFile', async function (req, res) {
      async function insertDatabase(data) {
        if(data.length >=512) {
          res.send({
            code: 1,
            message: '同一设备下节点不得超过512个'
          })
          return;
        }
        //清空该设备下的tag
        const counts = await knex('tag')
          .where('parent_id', '=', req.query.parent_id)
          .del()
    
        data = data.map(item => {
          let obj = {id: uuidv4()};
          for(let key in item){
            const newKey = key.slice(key.lastIndexOf('(')+1, key.lastIndexOf(')'));
            obj[newKey] = item[key];

          }
          return obj;
        })
        knex('tag')
          .insert(data)
          .then(row => {
            res.send({
              code: 0,
              message: '导入节点成功'
            })
          })
          .catch(err => {
            console.log(err)
            res.send({
              code: 1,
              message: err
            })
          })
      }


      const form = formidable();
      form.parse(req, (err, field, file) => {
        const workbook = xlsx.read(file.file.path, { type: 'file' });
        let data = [];
        const sheetNames = workbook.SheetNames; // 返回 ['sheet1', ...]
        for (const sheetName of sheetNames) {
          const worksheet = workbook.Sheets[sheetName];
          const d = xlsx.utils.sheet_to_json(worksheet);
          data = [...data, ...d]
        }
        insertDatabase(data);
      })
    })



    //根据parent_id查询tag
    app.post('/tag', function (req, res) {
      knex('tag')
        .where({ 'parent_id': req.body.parent_id })
        .select('*').then(rows => {
          res.send({
            code: 0,
            data: rows
          })
        })
        .catch(err => {
          res.send({
            code: 1,
            message: err
          })
        })
    })
    //模糊查询查询tag
    app.post('/tag/queryList', function (req, res) {
      const { page, size } = req.query;
      if (!req.body.chanel_no) {
        knex('tag')
          .limit(size)
          .offset((page - 1) * size)
          .select('*')
          .then(rows => {
            knex('tag')
              .count('id as total')
              .then(counts => {
                res.send({
                  code: 0,
                  data: rows,
                  total: counts[0].total
                })
              })

          })
        return;
      }
      knex('tag')
        .where('gw_id', '=', req.body.gw_id)
        .andWhere('chanel_no', 'like', req.body.chanel_no)
        .limit(size)
        .offset((page - 1) * size)
        .select('*')
        .then(rows => {
          knex('tag')
            .count('id as total')
            .then(counts => {
              res.send({
                code: 0,
                data: rows,
                total: counts[0].total
              })
            })
        })
        .catch(err => {
          console.log(err)
          res.send({
            code: 1,
            message: err
          })
        })
    })

    //删除tag
    app.post('/tag/del', function (req, res) {
      knex
        .raw('PRAGMA foreign_keys=ON')
        .then(() => {

          knex('tag')
            .where('id', req.body.id)
            .del()
            .then(row => {
              res.send({
                code: 0,
                data: 'tag删除成功'
              })
            })
            .catch(err => {
              res.send({
                code: 1,
                message: err
              })
            })

        })
    })


    //更新tag
    app.post('/tag/update', function (req, res) {
      const data = req.body;
      const id = data.id;
      delete data.id;
      knex('tag')
        .where('id', '=', id)
        .update({
          ...data
        })
        .then(row => {
          res.send({
            code: 0,
            data: '更新tag成功'
          })
        })
        .catch(err => {
          res.send({
            code: 1,
            message: err
          })
        })
    })
  }
}

